package com.zzzy.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.zzzy.controller.UserController;
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author John Yan
 * @Date 2019-01-10
 * @Description 动态数据源类
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    //指定默认数据源(springboot2.0默认数据源是hikari如何想使用其他数据源可以自己配置)
    private static final String DATASOURCE_TYPE_DEFAULT = "com.alibaba.druid.pool.DruidDataSource";

    private Map<Object, Object> dynamicTargetDataSources;

    @Override
    protected Object determineCurrentLookupKey() {
        String key = DynamicDataSourceContextHolder.getDataSource();
        return key;
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.dynamicTargetDataSources = targetDataSources;
    }

    @Override
    protected DataSource determineTargetDataSource() {

        String dbid = DynamicDataSourceContextHolder.getDataSource();
        logger.debug("tenent:" +dbid);

        if(!dynamicTargetDataSources.containsKey(dbid)){
            logger.debug("数据源"+dbid+"不存在,正在创建...");

            Map<String, Object> dsMap = new HashMap<>();
            dsMap.put("driverClassName", "com.mysql.jdbc.Driver");
            dsMap.put("url", "jdbc:mysql://10.61.0.220:3306/"+dbid+"?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
            dsMap.put("username", "root");
            dsMap.put("password", "123456");
            DataSource newDataSource = buildDataSource(dsMap);
            dynamicTargetDataSources.put(dbid, newDataSource);

            super.afterPropertiesSet();

            return newDataSource;
        }

        DataSource dataSource = super.determineTargetDataSource();

        return dataSource;
    }

    // 测试数据源连接是否有效
    private boolean testDatasource( String driveClass, String url, String username, String password) {
        try {
            Class.forName(driveClass);
            DriverManager.getConnection(url, username, password);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static DataSource buildDataSource(Map<String, Object> dataSourceMap) {
        try {
            Class<? extends DataSource> dataSourceType;
            dataSourceType = (Class<? extends DataSource>) Class.forName(DATASOURCE_TYPE_DEFAULT);
            String driverClassName = dataSourceMap.get("driverClassName").toString();
            String url = dataSourceMap.get("url").toString();
            String username = dataSourceMap.get("username").toString();
            String password = dataSourceMap.get("password").toString();
            // 自定义DataSource配置
            Properties proterties = new Properties();
            proterties.put("driverClassName", driverClassName);
            proterties.put("url", url);
            proterties.put("username", username);
            proterties.put("password", password);
            return DruidDataSourceFactory.createDataSource(proterties);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}



